import requests,json
 

class 企业微信应用():
    """  通过api调用实现 信息发送


 

    """
    one = -1  # 首次运行
    res = {}  # 资源
    access_token = ""
    
    def 发送消息给uid(self, uid: str , msg: str,appid:int = 1000012)  :
        """创建 本月第一天 + 下个月第一天
        
        Args:
            year (int): 年份
            mon (int): 月份
        
        Returns:
            dict: {}
        
        """
        url = "https://qyapi.weixin.qq.com/cgi-bin/message/send"
        body = {
           "touser" : uid,
           "msgtype" : "text",
           "agentid" : appid,
           "text" : {
               "content" : msg
           }
        }
        headers = {'Content-Type': 'application/json'}
        params = {'access_token': self.access_token }
        response = requests.post(
            url,
            params=params,      # URL参数
            headers=headers,    # 请求头
            json=body           # 请求体（自动转换为JSON）
            # 或者用data=body（表单格式）
        )
        return response.json()
 
    def 标签组内所有用户(self,gid:int):
        """ 返回查询 结构的json  占位替换
            args:
                gid:int
                
            returns:list  [{}]
        """
        url = "https://qyapi.weixin.qq.com/cgi-bin/tag/get"

        #headers = {'Content-Type': 'application/json'}
        params = {'access_token': self.access_token,"tagid" : gid}
        response = requests.post(
            url,
            params=params,      # URL参数
            #headers=headers,    # 请求头
            #json=body           # 请求体（自动转换为JSON）
            # 或者用data=body（表单格式）
        )
        uids = [ i  for i in response.json()["userlist"] ]
        return uids
 
 
    def 标签组内所有用户id(self,gid:int):
        """ 返回查询 结构的json  占位替换
            args:
                gid:int
                
            returns:str uid   "abc|def|jkl"
        """
        
        uids = [ i["userid"] for i in self.标签组内所有用户(gid) ]
        return "|".join(uids)
 
    
        
    def 获取token(self,id:str,secret:str)->str:
        """ 通过密钥 得到通信令牌
        args:
            id: 企业id
            secret:  密钥
        returns:
            str: token令牌
        """
        url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken"
        
        body = {
        "corpid": id,
        "corpsecret": secret
        }
        headers = {'Content-Type': 'application/json'}
        #params = {'access_token': self.access_token }
        response = requests.post(
            url,
            #params=params,      # URL参数
            headers=headers,    # 请求头
            json=body           # 请求体（自动转换为JSON）
            # 或者用data=body（表单格式）
        )
        jdata =  response.json()
        self.access_token = jdata['access_token']
        
        
 
def main(gid,year,mon):
 
    self = 企业微信应用()
    k = {
    "corpid": "ww9c0c7927b70a1368",
    "corpsecret": "liSANMa-e1atIqLlKSIQKpsB1YaZ0HbLBiaHGednV_A"
    }
    self.获取token(k['corpid'],k['corpsecret'])
    
    
    
    import 补考勤报告   
    #补考勤报告 = reload(补考勤报告)
    bk = 补考勤报告.补考勤报告()
    
    #mon=4
    #year=2025
    ignore =[] # ["2025-01-30","2025-05-31"]
    
    for row in self.标签组内所有用户(gid):
        #print(row["name"],row["userid"])
        print(row )
        try:
            # 生成信息
            msg = bk.补卡信息生成(year,mon,row["name"],ignore)
            if msg:
                # 发送信息
                self.发送消息给uid(row["userid"],msg)

        except Exception as e:
            print(row["name"],row["userid"],"发送错误",e)






if __name__ == "__main__":
    
    group = 1  #// 1群发 2 测试
    mon=8
    year=2025
    #print(main(name,year,mon))
    #do(nameList,year,mon)
    main(group,year,mon)
